//
//  JoinViewController.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/4/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "JoinViewController.h"
#import "MapViewController.h"
#import "GruphotoTabBarController.h"
#import "EventJoinCell.h"
#import "EventDetailViewController.h"
#import "GruphotoAppDelegate.h"
#import "Event.h"
#import "User.h"
#import "Photo.h"


#define kPasscodeTag    99

@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"background_navigation_bar.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

@interface JoinViewController (PrivateMethods)
- (void)addBarItems;
- (void)resignKeyboard;
@end

@implementation JoinViewController
@synthesize joinSearchBar, joinTableView, maskView;
@synthesize joinableEvents, eventsNeedDisplay, selectedEvent;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"background_navigation_bar.png"]
                                                      forBarMetrics:UIBarMetricsDefault];
    }
    joinSearchBar.backgroundImage = [UIImage imageNamed:@"background_searchbar.png"];
    [self addBarItems];
    joinTableView.bounces = YES;
    joinTableView.backgroundColor = [UIColor colorWithRed:226/255.0 green:231/255.0 blue:237/255.0 alpha:1.0];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if (![userDefaults objectForKey:@"ShowJoiningMessage"]) {
        [userDefaults setObject:@"NO" forKey:@"ShowJoiningMessage"];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Select event to join", @"")
                                                            message:NSLocalizedString(@"Select the event from list or map to join in. you can join only to the closest enent near you", @"")
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"Cancel", @"")
                                                  otherButtonTitles:NSLocalizedString(@"Continue", @""), nil];
        alertView.tag = AlertViewTagFirstMessage;
        [alertView show];
        [alertView release];        
    }
    else {
        [self getJoinableEvents];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.joinSearchBar = nil;
    self.joinTableView = nil;
    self.maskView = nil;
}

- (void)dealloc {
    self.selectedEvent = nil;
    self.joinableEvents = nil;
    self.eventsNeedDisplay = nil;
    [joinTableView release];
    [joinSearchBar release];
    [maskView release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Private methods
- (void)addBarItems {    
    UIImageView *titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"title_gruphoto.png"]];
    self.navigationItem.titleView = titleImageView;
    [titleImageView release];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setBounds:CGRectMake(0, 0, 51, 30)];
    [cancelButton setBackgroundImage:[UIImage imageNamed:@"button_cancel.png"] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
    self.navigationItem.leftBarButtonItem = cancelButtonItem;
    [cancelButtonItem release];
    
    UIButton *mapButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [mapButton setBounds:CGRectMake(0, 0, 51, 30)];
    [mapButton setBackgroundImage:[UIImage imageNamed:@"button_map.png"] forState:UIControlStateNormal];
    [mapButton addTarget:self action:@selector(mapButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *mapButtonItem = [[UIBarButtonItem alloc] initWithCustomView:mapButton];
    self.navigationItem.rightBarButtonItem = mapButtonItem;
    [mapButtonItem release];
}

- (void)resignKeyboard {
    [joinSearchBar resignFirstResponder];
    maskView.hidden = YES;
}

#pragma mark - Action methods
- (IBAction)cancelButtonPressed:(id)sender {
    [self resignKeyboard];
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)mapButtonPressed:(id)sender {
    [self resignKeyboard];
    MapViewController *mapViewController = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil];
    mapViewController.mapMode = EventMapModeNormal;
    whereEventCome = EventDetailModeJoin;
    mapViewController.events = joinableEvents;
    [self.navigationController pushViewController:mapViewController animated:YES];
    GruphotoTabBarController *tabBarController = (GruphotoTabBarController *)self.tabBarController;
    [tabBarController hidesFakeTabBar:YES];
    [mapViewController release];
    mapViewController = nil;
}

- (IBAction)maskViewTapped:(id)sender {
    [self resignKeyboard];
}

#pragma mark - Custom methods
- (void)showAlertPassword {
    UIAlertView *alertView;
    UITextField *passcodeField;
    NSString *message;
    
    alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Private Event", @"")
                                           message:nil
                                          delegate:self
                                 cancelButtonTitle:NSLocalizedString(@"Cancel", @"")
                                 otherButtonTitles:NSLocalizedString(@"OK", @""), nil];
    if ([Global systemVersion] >= 5.0) {
        alertView.alertViewStyle = UIAlertViewStyleSecureTextInput;
        passcodeField = [alertView textFieldAtIndex:0];
        message = NSLocalizedString(@"You have enter into a private area. Please enter password", @"");
    }
    else {
        passcodeField = [[[UITextField alloc] initWithFrame:CGRectMake(12, 90, 260, 30)] autorelease];
        passcodeField.borderStyle = UITextBorderStyleRoundedRect;
        [passcodeField setSecureTextEntry:YES];
        [alertView addSubview:passcodeField];
        message = NSLocalizedString(@"You have enter into a private area. Please enter password\n\n", @"");
    }
    
    passcodeField.placeholder = @"Password";
    passcodeField.font = [UIFont systemFontOfSize:17];
    passcodeField.returnKeyType = UIReturnKeyDone;
    passcodeField.delegate = self;
    passcodeField.tag = kPasscodeTag;
    passcodeField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    [passcodeField becomeFirstResponder];
    
    alertView.tag = AlertViewTagEnterCode;
    alertView.message = message;
    [alertView show];
    [alertView release];
}

- (void)getDetailsOfEventWithId:(NSInteger)eventId andStatus:(NSString *)status {
    [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:status];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[GruphotoAppDelegate sharedDelegate].loggedInUser.token forKey:kUserToken];
    [params setObject:[NSString stringWithFormat:@"%d", selectedEvent.eventId] forKey:kEventId];
    [TNHRequestHelper sendPostRequest:kGetDetailsOfEventUrl
                              withTag:RequestTagGetDetailsOfEvent
                               params:params
                             delegate:self];
}

- (void)getJoinableEvents {
    [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Loading..."];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[GruphotoAppDelegate sharedDelegate].loggedInUser.token forKey:kUserToken];
    NSNumber *longitue = [NSNumber numberWithDouble:[GruphotoAppDelegate sharedDelegate].currentLocation.coordinate.longitude];
    NSNumber *latitude = [NSNumber numberWithDouble:[GruphotoAppDelegate sharedDelegate].currentLocation.coordinate.latitude];
    [params setObject:longitue forKey:kLongitude];
    [params setObject:latitude forKey:kLatitude];
    [params setObject:@"100" forKey:kDistance];
    NSLog(@"params: %@", params);
    [TNHRequestHelper sendPostRequest:kGetJoinableEventsUrl
                              withTag:RequestTagGetJoinableEvents
                               params:params
                             delegate:self];
}

#pragma mark - Custom methods
- (void)resetSearch {
    NSMutableArray *eventsCopy = [joinableEvents mutableCopy];
	self.eventsNeedDisplay = eventsCopy;
	[eventsCopy release];
}

- (void)handleSearchForTerm:(NSString *)searchTerm {
	NSMutableArray *eventsToRemove = [[NSMutableArray alloc] init];
	[self resetSearch];
    for (Event *event in eventsNeedDisplay) {
        NSString *eventName = event.eventTitle;
        NSString *authorName = event.creater.firstName;
        NSString *placeName = event.placeName;
        if ([eventName rangeOfString:searchTerm
                             options:NSCaseInsensitiveSearch].location == NSNotFound &&
            [placeName rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound &&
            [authorName rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound) {
            [eventsToRemove addObject:event];
        }
    }
    [eventsNeedDisplay removeObjectsInArray:eventsToRemove];
	[eventsToRemove release];
	[joinTableView reloadData];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (alertView.tag == AlertViewTagFirstMessage) {
        if (buttonIndex == 0) {
            [self cancelButtonPressed:nil];
        }
        else {
            [self getJoinableEvents];
        }
    }
    else if (alertView.tag == AlertViewTagEnterCode) {
        if (buttonIndex == 0) {
            // do nothing
        }
        else {
            UITextField *textField = nil;
            for (UIView *view in alertView.subviews) {
                if ([view isKindOfClass:[UITextField class]]) {
                    textField = (UITextField *)view;
                    break;
                }
            }
            NSString *passcode = textField.text;
            if (passcode.length == 0) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning message"
                                                                    message:@"You must enter password"
                                                                   delegate:self
                                                          cancelButtonTitle:@"Cancel"
                                                          otherButtonTitles:@"Continue", nil];
                alertView.tag = AlertViewTagPasscodeMissing;
                [alertView show];
                [alertView release];
            }
            else {
                if (![passcode isEqualToString:selectedEvent.code]) {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning message"
                                                                        message:@"Wrong password,\n please try again"
                                                                       delegate:self
                                                              cancelButtonTitle:@"Cancel"
                                                              otherButtonTitles:@"Continue", nil];
                    alertView.tag = AlertViewTagPasscodeMissing;
                    [alertView show];
                    [alertView release];                    
                }
                else {
                    [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Connecting..."];
                    NSMutableDictionary *params = [NSMutableDictionary dictionary];
                    [params setObject:[GruphotoAppDelegate sharedDelegate].loggedInUser.token forKey:kUserToken];
                    [params setObject:selectedEvent.code forKey:kCode];
                    [params setObject:[NSString stringWithFormat:@"%d", selectedEvent.eventId] forKey:kEventId];
                    [TNHRequestHelper sendPostRequest:kJoinToEventUrl
                                              withTag:RequestTagJoinToEvent
                                               params:params
                                             delegate:self];                    
                }
            }
        }        
    }
    else if (alertView.tag == AlertViewTagPasscodeMissing) {
        if (buttonIndex == 1) {
            [self showAlertPassword];
        }
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    switch (textField.tag) {
        case kPasscodeTag: {
            UIAlertView *alertView = (UIAlertView *)textField.superview;
            [alertView dismissWithClickedButtonIndex:1 animated:YES];            
            break;
        }
        default:
            break;
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString* proposedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    textField.text = [proposedString uppercaseString];
    return NO;
}

#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    maskView.hidden = NO;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self resignKeyboard];
	NSString *searchTerm = [searchBar text];
	[self handleSearchForTerm:searchTerm];    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchTerm {
	if ([searchTerm length] == 0) {
		[self resetSearch];
		[joinTableView reloadData];
		return;
	}
	[self handleSearchForTerm:searchTerm];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return eventsNeedDisplay.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *EventJoinCellId = @"EventJoinCell";
    EventJoinCell *cell = (EventJoinCell *)[tableView dequeueReusableCellWithIdentifier:EventJoinCellId];
    if (cell == nil) {
        cell = [EventJoinCell cellFromNib];
    }
    Event *event = [eventsNeedDisplay objectAtIndex:indexPath.row];
    if (event.creater.avatarImage != nil) {
        cell.avatarImageView.image = event.creater.avatarImage;
    }
    else {
        if (event.creater.avatarUrl.length > 0) {
            NSURL *avatarUrl = [NSURL URLWithString:event.creater.avatarUrl];
            [cell.avatarImageView setImageWithURL:avatarUrl
                                 placeholderImage:[UIImage imageNamed:@"no_avatar.png"]
                                          options:SDWebImageProgressiveDownload];
        }
        else {
            cell.avatarImageView.image = [UIImage imageNamed:@"no_avatar.png"];
        }
    }
    cell.eventTitleLabel.text = event.eventTitle;
    cell.numberOfLikesLabel.text = [NSString stringWithFormat:@"%d", event.numberOfLikes];
    cell.numberOfPeoplesLabel.text = [NSString stringWithFormat:@"%d", event.numberOfMembers];
    cell.numberOfPhotosLabel.text = [NSString stringWithFormat:@"%d", event.numberOfImages];
    if (event.isPrivate) {
        cell.detailLabel.text = @"Private event";
    }
    else {
        cell.detailLabel.text = [NSString stringWithFormat:@"Created by: %@", event.creater.firstName];
    }
    cell.distanceLabel.text = [NSString stringWithFormat:@"%0.0fM", event.distance];
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.selectedEvent = [eventsNeedDisplay objectAtIndex:indexPath.row];
    if (selectedEvent.creater.userId == [GruphotoAppDelegate sharedDelegate].loggedInUser.userId ||
        selectedEvent.isJoining) {
        // Get event details
        [self getDetailsOfEventWithId:selectedEvent.eventId andStatus:@"Loading..."];
    }
    else
    if (selectedEvent.isPrivate) {
        [self showAlertPassword];
    }
    else {
        [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Connecting..."];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:[GruphotoAppDelegate sharedDelegate].loggedInUser.token forKey:kUserToken];
        [params setObject:selectedEvent.code forKey:kCode];
        [params setObject:[NSString stringWithFormat:@"%d", selectedEvent.eventId] forKey:kEventId];
        [TNHRequestHelper sendPostRequest:kJoinToEventUrl
                                  withTag:RequestTagJoinToEvent
                                   params:params
                                 delegate:self];
    }
}

#pragma mark - ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    NSDictionary *response = (NSDictionary *)[TNHRequestHelper objectWithString:request.responseString];
    NSInteger errorCode = [[response objectForKey:kErrorCode] integerValue];
    if (errorCode == ErrorCodeNone) {
            NSLog(@"listEvent data: %@", response);
        if (request.tag == RequestTagGetJoinableEvents) {
            self.joinableEvents = [NSMutableArray array];
            NSArray *events = [response objectForKey:kEvents];
            for (NSDictionary *dict in events) {
                Event *event = [[Event alloc] init];
                event.eventId = [[dict objectForKey:kEventId] integerValue];
                event.eventTitle = [dict objectForKey:kTitle];
                event.placeName = [dict objectForKey:kPlaceName];
                event.placeAddress = [dict objectForKey:kPlaceAddress];
                event.longitude = [dict objectForKey:kLongitude];
                event.latitude = [dict objectForKey:kLatitude];
                event.eventEnd = [[dict objectForKey:kTimeLimit] integerValue];
                event.eventPasstime = [[dict objectForKey:kPassTime] integerValue];
                event.numberOfImages = [[dict objectForKey:kNumPhoto] integerValue];
                event.numberOfLikes = [[dict objectForKey:kNumLike] integerValue];
                event.numberOfMembers = [[dict objectForKey:kNumMember] integerValue];
                event.isPrivate = ![[dict objectForKey:kIsPublic] boolValue];
                event.code = [dict objectForKey:kCode];
                event.distance = [[dict objectForKey:kDistance] floatValue];
                event.isJoining = [[dict objectForKey:kJoining] boolValue];
                NSDictionary *dictUser = [dict objectForKey:kUser];
                User *creater = [[User alloc] init];
                creater.userId = [[dictUser objectForKey:kUserId] integerValue];
                creater.firstName = [dictUser objectForKey:kFirstName];
                creater.lastName = [dictUser objectForKey:kLastName];
                if (![[dictUser objectForKey:kPhoto] isEqual:[NSNull null]]) {
                    creater.avatarUrl = [dictUser objectForKey:kPhoto];
                    if ([creater.avatarUrl rangeOfString:@"http" options:NSCaseInsensitiveSearch].location == NSNotFound ||
                        [creater.avatarUrl rangeOfString:@"https" options:NSCaseInsensitiveSearch].location == NSNotFound) {
                        creater.avatarUrl = [NSString stringWithFormat:@"%@%@", kServerUrl, creater.avatarUrl];
                    }
                }
                if (![[dictUser objectForKey:kSocialId] isEqual:[NSNull null]]) {
                    creater.socialId = [dictUser objectForKey:kSocialId];
                }
                creater.numberOfFollowers = [[dictUser objectForKey:kNumFollower] integerValue];
                creater.numberOfLikes = [[dictUser objectForKey:kNumLike] integerValue];
                creater.numberOfPhotos = [[dictUser objectForKey:kNumPhoto] integerValue];
                event.creater = creater;
                [creater release];
                
                NSArray *photos = [response objectForKey:kImages];
                for (NSString *urlString in photos) {
                    if ([urlString rangeOfString:@"http" options:NSCaseInsensitiveSearch].location == NSNotFound ||
                        [urlString rangeOfString:@"https" options:NSCaseInsensitiveSearch].location == NSNotFound) {
                        urlString = [NSString stringWithFormat:@"%@%@", kServerUrl, urlString];
                    }
                    Photo *_photo = [[Photo alloc] initWithSourcePath:urlString];
                    [event.photos addObject:_photo];
                    [_photo release];
                    [[SDWebImageManager sharedManager] downloadWithURL:[NSURL URLWithString:urlString]
                                                              delegate:nil
                                                               options:0];
                }
                [joinableEvents addObject:event];
                [event release];
            }
            [joinableEvents sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                Event *event1 = (Event *)obj1;
                Event *event2 = (Event *)obj2;
                return event1.distance > event2.distance;
            }];
            [self resetSearch];
            [joinTableView reloadData];            
        }
        else if (request.tag == RequestTagJoinToEvent ||
                 request.tag == RequestTagGetDetailsOfEvent) {
            NSLog(@"one event data: %@", response);
            EventDetailViewController *eventDetailViewController = [[EventDetailViewController alloc] initWithNibName:@"EventDetailViewController" bundle:nil];
            eventDetailViewController.eventDetail = response;
            eventDetailViewController.hidesBottomBarWhenPushed = YES;
            eventDetailViewController.detailMode = EventDetailModeJoin;
            selectedEvent.numberOfImages = [[response objectForKey:kNumPhoto] integerValue];
            selectedEvent.numberOfMembers = [[response objectForKey:kNumMember] integerValue];
            selectedEvent.numberOfLikes = [[response objectForKey:kNumLike] integerValue];
            selectedEvent.eventPasstime = [[response objectForKey:kPassTime] integerValue];
            NSArray *arrayUsers = [response objectForKey:@"users"];
            for (NSDictionary *user in arrayUsers) {
                User *member = [[User alloc] init];
                member.firstName = [user objectForKey:kFirstName];
                member.lastName = [user objectForKey:kLastName];
                member.numberOfFollowers = [[user objectForKey:kNumFollower] integerValue];
                member.numberOfLikes = [[user objectForKey:kNumLike] integerValue];
                member.numberOfPhotos = [[user objectForKey:kNumPhoto] integerValue];
                if (![[user objectForKey:kPhoto] isEqual:[NSNull null]]) {
                    member.avatarUrl = [user objectForKey:kPhoto];
                    if ([member.avatarUrl rangeOfString:@"http" options:NSCaseInsensitiveSearch].location == NSNotFound ||
                        [member.avatarUrl rangeOfString:@"https" options:NSCaseInsensitiveSearch].location == NSNotFound) {
                        member.avatarUrl = [NSString stringWithFormat:@"%@%@", kServerUrl, member.avatarUrl];
                    }                    
                }
                member.userId = [[user objectForKey:kUserId] integerValue];
                if (![[user objectForKey:kSocialId] isEqual:[NSNull null]]) {
                    member.socialId = [user objectForKey:kSocialId];
                }
                [selectedEvent.users addObject:member];
                [member release];
            }
            eventDetailViewController.event = selectedEvent;
            [self.navigationController pushViewController:eventDetailViewController animated:YES];          
            NSArray *viewControllers = [NSArray arrayWithObject:[self.navigationController.viewControllers lastObject]];
            [self.navigationController setViewControllers:viewControllers animated:NO];
            [eventDetailViewController release];            
        }
    }
    else {
        NSString *errorMessage = [response objectForKey:kErrorMessage];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error message"
                                                            message:errorMessage
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Connection error"
                                                        message:@"Internet is down, please try again"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

#pragma mark - SDWebImageDownloaderDelegate
-(void)imageDownloader:(SDWebImageDownloader *)downloader didFailWithError:(NSError *)error{
    NSLog(@"download image error: %@",error.localizedDescription);
}

-(void)imageDownloader:(SDWebImageDownloader *)downloader didFinishWithImage:(UIImage *)image{
}
@end
